<template>
	<cu-custom :isBack="true">
		<template #title>上传材料</template>
	</cu-custom>
	<view class="page-content">
		<view class="default-box theme-shadow mb-3">
			<view class="middle-text text-bold mb-3">上传图片（最大5MB）</view>
			
			<view class="cu-form-group">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="viewImage" :data-url="imgList[index]">
					 <image :src="item.serverPath" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="delImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="modalShow" v-if="imgList.length < 9">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="default-box theme-shadow mb-3">
			<view class="middle-text text-bold mb-3">上传相关文档（最大5MB）</view>
			
			<view class="cu-form-group">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" v-for="(item, index) in fileList" :key="index" @tap="viewFile(item)" :data-url="fileList[index]">
						<image :src="calcIcon(item.suffix)" mode="aspectFill" />
						<view class="file-name text-ellipsis-1">{{ item.filename }}</view>
						<view class="cu-tag bg-red" @tap.stop="delFile" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="handleChooseFile" v-if="fileList.length < 9">
						<text class='cuIcon-add'></text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="text-in default-box theme-shadow mb-3">
			<textarea
				:enable-native="false"
				placeholder="请输入文字"
				maxlength="500"
				cols="30"
				rows="10"
				style="height:200rpx"
				v-model="textarea"
			></textarea>
			<!-- #ifdef MP-ALIPAY -->
			<view class="voice-in" @click="navToVoice('totext')">
				<text class="cuIcon-voicefill text-gray"></text>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<ToText @updateText="updateText" />
			<!-- #endif -->
		</view>
		
		<view style="height: 40rpx;"></view>
		<view class="mb-4">
			<CuButton size="small" :disabled="submitDisable" @click="handleSubmit">提交</CuButton>
		</view>
	</view>
	
	
	<Modal ref="modal">
		<view class="padding-xl">
			<view class="flex justify-around">
				<view class="text-black" @click="chooseImage('camera')">
					<view class="icon text-blue"><text class="cuIcon-camerafill"></text></view>
					<view class="icon-text">拍照</view>
				</view>
				<view class="text-black" @click="chooseImage('album')">
					<view class="icon text-blue"><text class="cuIcon-picfill"></text></view>
					<view class="icon-text">相册</view>
				</view>
			</view>
		</view>
	</Modal>
	
</template>

<script setup lang="ts">
import { onLoad, onUnload } from "@dcloudio/uni-app"
import { reactive, ref, type Ref } from 'vue';
import CuButton from "@/components/CuButton.vue"
import { uploadFile } from "@/api/common.js"
import { uploadRect } from "@/api/mission.js"
import { router } from "@/router"
import { obj2str } from "@/utils/base"
import store from "@/store/index.js"
import env from "@/env"
import { voice2Text, downloadFile } from "@/utils/common"
import Record from "@/components/Record.vue"
import path from "path-browserify"
import ToText from "@/components/ToText.vue"
import { createObjectBlob } from "@/utils/base"
import Modal from "@/components/Modal.vue"
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

interface IFile {
	localPath: string
	serverPath: string
	suffix: string
	filename: string
}
interface IImage {
	filename: string
	serverPath: string
}

const props = defineProps({
	mission_id: {
		type: String,
		default: null
	}
})

let rect_id = null
let media_id:Ref<string> = ref("") // 录音文件ID
let duration:Ref<string> = ref("")
let to_text_media_id = null

const record: Ref<any> = ref()
let recording_type = null
const textareaFocus: Ref<boolean> = ref(false)
const submitDisable: Ref<boolean> = ref(false)
const textarea: Ref<string> = ref("")
const imgList: Ref<IImage[]> = ref([] as IImage[])
const fileList: Ref<IFile[]> = ref([] as IFile[])
const isNotice: Ref<boolean> = ref(false)
const userInfo = reactive(store.getters.userInfo)

let recorderManager = null
let isSubmitLeave = false
const modal = ref()

const switchNotice = () => {
	isNotice.value = !isNotice.value
}

const calcIcon = (suffix:string):string => {
	if (suffix === 'docx') {
		return env.H5_RELATIVE_URL + '/static/images/docx_icon.png'
	} else {
		return env.H5_RELATIVE_URL + '/static/images/otherfile_icon.png'
	}
}
const modalShow = () => {
	modal.value.show()
}
const viewImage = (e:any):void => {
	const imgViewList = []
	imgList.value.map((image) => {
		imgViewList.push(image.serverPath)
	})
	console.log("viewimg e", e)
	uni.previewImage({
		urls: imgViewList,
		current: e.currentTarget.dataset.url.serverPath
	})
}

const delImg = (e:any):void => {
	uni.showModal({
		title: '删除',
		content: '确定要删除这张图片？',
		cancelText: '取消',
		confirmText: '确认',
		success: res => {
			if (res.confirm) {
				imgList.value.splice(e.currentTarget.dataset.index, 1)
			}
		}
	})
}
const chooseImage = (type: string = "album"):void => {
	modal.value.hide()
	if (type === "album") {
		dd.chooseImage({})
			.then(async (res: any) => {
				uni.showLoading({
					title: "上传中"
				})
				try {
					for (let item of res.images) {
						const file = await uploadProcess(item.path)
						if (file.code === 200) {
							imgList.value.push({
								filename: file.originalFilename,
								serverPath: file.url
							})
						}
					}
					uni.hideLoading()
				} catch (err) {
					uni.hideLoading()
				}
			})
			.catch((err: any) => {
				console.log(err)
				// uni.showToast({
				// 	icon: "none",
				// 	title: JSON.stringify(err)
				// })
			})
	} else {
		dd.takePhoto().then(async (res: any) => {
			// uni.showToast({
			// 	icon: "none",
			// 	title: JSON.stringify(res)
			// })
			uni.showLoading({
				title: "上传中"
			})
			try {
				const file = await uploadProcess(res.path)
				if (file.code === 200) {
					imgList.value.push({
						filename: file.originalFilename,
						serverPath: file.url
					})
				}
				uni.hideLoading()
			} catch (err) {
				uni.hideLoading()
			}
		}).catch(async (err: any) => {
			// uni.showToast({
			// 	icon: "none",
			// 	title: JSON.stringify(err)
			// })
		})
	}
}



const viewFile = (file: IFile):void => {
	// #ifdef H5
	if (store.getters.osName === "ios") {
		router.push("/pages/index/word?title=" + file.filename + "&filepath=" + file.serverPath)
	} else {
		location.href = file.filename
	}
	// #endif
}

const delFile= (e:any):void => {
	uni.showModal({
		title: '删除',
		content: '确定要删除这个文件？',
		cancelText: '取消',
		confirmText: '确认',
		success: res => {
			if (res.confirm) {
				fileList.value.splice(e.currentTarget.dataset.index, 1)
			}
		}
	})
}
const handleChooseFile = ():void => {
	dd.chooseFile({
		// "maxNum": 3
		multiSelection: true
	}).then(async (res) => {
		uni.showLoading({
			title: "上传中"
		})
		try {
			for (let file of res.files) {
				const result = await uploadProcess(file.path)
					.catch((err) => {
						uni.showToast({
							icon: "none",
							title: "上传失败" + JSON.stringify(err)
						})
						uni.hideLoading()
					})
				
				if (result.code === 200) {
					fileList.value.push({
						localPath: file.path,
						serverPath: result.url,
						suffix: result.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
						filename: result.originalFilename,
					})
				}
			}
			uni.hideLoading()
		} catch (err) {
			uni.hideLoading()
		}
	}).catch((err) => {
		console.log(err)
	})
}

const uploadProcess = async (filePath:string = ""): Promise<any> => {
	let res = null
	// #ifdef MP-ALIPAY
	res = await uploadFile({
		filePath,
		name: path.basename(filePath)
	})
	// #endif
	// #ifdef H5
	try {
		const uploadRes = await dd.uploadFile({
			filePath: [ filePath ]
		})
		const result = await downloadFile({
			media_id: uploadRes[0],
			ext: filePath.match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1]
		})
		res = {
			code: 200,
			url: result.filepath,
			originalFilename: path.basename(filePath)
		}
	} catch (err) {
		throw err
	}
	
	// #endif
	
	return res
}


const navToVoice = (recording_type = "record") => {
	const query = obj2str({
		mediaId: media_id.value,
		duration: duration.value,
		recording_type: recording_type,
		callback: "/pages/mission/upload"
	})
	// console.log(`${env.DD_SCHEME}${env.DD_HOST}/action/open_app?type=1&offline=false&url=${encodeURIComponent(env.MINI_APP_URL + "pages/index/recording?" + query)}`)
	dd.openLink({
		url: `${env.DD_SCHEME}${env.DD_HOST}/action/open_app?type=1&offline=false&url=${encodeURIComponent(env.MINI_APP_URL + "pages/index/recording?" + query)}`
	}).then((res:any) => {
		console.log("success")
		console.log(res)
	}).catch((err:any) => {
		console.log("error")
		console.log(err)
	})
}


const updateText = (e: string) => {
	textarea.value = e
}

/**
 * 语音文件转文字
 */
const media2Text = ():void => {
	
	voice2Text(to_text_media_id)
		.then((res) => {
			textarea.value = res
		})
}

/**
 * 提交日志
 */
const handleSubmit = ():void => {
	if (!textarea.value && imgList.value.length === 0 && fileList.value.length === 0) {
		uni.showToast({
			title: "请至少提交一项材料"
		})
		return 
	}
	submitDisable.value = true
	uni.showLoading({
		title: "上传中"
	})
	const files = []
	imgList.value.map((item) => {
		files.push({
			"fileName": item.filename,
			"fileUrl": item.serverPath
		})
	})
	fileList.value.map((item) => {
		files.push({
			"fileName": item.filename,
			"fileUrl": item.serverPath
		})
	})
	
	uploadRect({
		"rectificationTaskId": rect_id,
		"subDescription": textarea.value,
		"files": files,
	}).then(() => {
			uni.hideLoading()
			uni.showToast({
				icon: "success",
				title: "上传成功"
			})
			setTimeout(() => {
				isSubmitLeave = true
				router.back()
			}, 1000)
		})
}

onUnload(() => {
	// if (media_id.value || textarea.value || imgList.value.length > 0 || fileList.value.length > 0) {
	if (!isSubmitLeave) {
		const upload_rect_cache = {
			rect_id,
			textarea: textarea.value,
			imgList: imgList.value,
			fileList: fileList.value
		}
		uni.setStorageSync("rect_upload_cache_data", JSON.stringify(upload_rect_cache))
	}
	// }
})
onLoad(async (options) => {
	
	if (options.rect_id) {
		rect_id = options.rect_id
	}
	
	const rect_upload_cache_data = uni.getStorageSync("rect_upload_cache_data")
	uni.removeStorage({ key: "rect_upload_cache_data" })
	
	if (rect_upload_cache_data) {
		const upload_rect_cache = JSON.parse(rect_upload_cache_data)
		if (!rect_id || rect_id == upload_rect_cache.rect_id) {
			rect_id = upload_rect_cache.rect_id
			
			textarea.value = upload_rect_cache.textarea
			imgList.value = upload_rect_cache.imgList
			fileList.value = upload_rect_cache.fileList
		}
	}
})

</script>

<style lang="stylus" scoped>
.cu-form-group
	padding 0
.solids::after
	border 8rpx solid #3974df
.cuIcon-cameraadd, .cuIcon-add
	color #3974df!important

.text-in
	position: relative
	.voice-in
		position: absolute
		top: 46rpx
		right: 50rpx
		font-size 38rpx
		z-index: 99
.file-name
	position: absolute
	bottom: 0
	height: 20%
	text-align: center
	width: 100%
	color: #626262
.recording-row:active
	background: #eee
.recording-row
	padding 10rpx 40rpx
	background: #fff
	border-radius: 12rpx
.voice-box
	display: flex
	align-items: center
	height: 86rpx
	.play-title
		width: 80rpx
	.play-voice
		margin: 0 auto
		height: 66rpx
		width: 430rpx
		border-radius: 12rpx
		display: flex
		align-items: center
		font-weight: bold
		color #515151
		image
			width: 44rpx
			height: 44rpx
			padding: 11rpx
	.action
		width: 60rpx
		text-align: right
	.none-voice
		width: 430rpx
		
.icon
	font-size: 72rpx
.icon-text
	font-size: 24rpx
</style>